import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,  //开发环境基地址
  timeout: 10000
})
//请求拦截器
service.interceptors.request.use((config) => {
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})
//响应拦截器
service.interceptors.response.use((response) => {
  const { data, message, success } = response.data
  if (success) {
    return data
  }
  Message({ type: 'error', message: error.message })//通过element组件提示错误
  return Promise.reject(new Error(message))
}, async (error) => {
  //1.响应失败，token失效的情况
  if (error.response.status === 401) {
    //调用vuex方法，清除token和用户数据
    Message({ type: 'wanning', message: '登录超时，请重新登录' })
    await store.dispatch('user/logout')
    router.push('/')
    return Promise.reject(error)
  }
  Message({ type: 'error', message: error.message })
  return Promise.reject(error)
})

export default service